/**
 *
 */
// 1. 构建事件循环 eventloop
// 2. 往任务队列数组中push
// let taskQueue = []
// function eventLoop(){
//     const now = Date.now()
//     for(let i=0,len=taskQueue.length;i<len;i++) {
//         const { fn, startTime, delayTime,args } = taskQueue[i] || {}
//         if (now - startTime >= delayTime) {
//             fn(...args)
//             taskQueue[i] = null
//         }
//     }
//     taskQueue = taskQueue.filter(t => !!t)
//     requestAnimationFrame(eventLoop)
// }
var taskQueue = []
var timerId = 0

function setTimeout(fn, delayTime, ...args) {
  if (typeof fn !== "function") {
    throw new Error("fn must be an function")
  }
  timerId++
  taskQueue.push({ timerId, fn, startTime: Date.now(), delayTime, args })
  const eventLoop = () => {
    const now = Date.now()
    for (let i = 0, len = taskQueue.length; i < len; i++) {
      const { fn, startTime, delayTime, args } = taskQueue[i] || {}
      if (Date.now() - startTime >= delayTime) {
        fn.call(this, ...args)
        taskQueue[i] = null
      }
    }
    taskQueue = taskQueue.filter((t) => !!t)
    requestAnimationFrame(eventLoop)
  }
  eventLoop()
  return timerId
}
function clearTimeout(timer) {
  taskQueue = taskQueue.filter((t) => t.timerId !== timer)
}
// setTimeout((a, b, c, d) => console.log(a, b, c, d), 5000, 1, 2, 3, 4)
// setTimeout(() => console.log('a,b,c,d'), 5000)
// module.exports = { setTimeout }
function setInterval (fn, waitTime, ...args) {
  if (typeof fn !== "function") {
    throw new Error("fn must be an function")
  }
  timerId++
  taskQueue.push({ timerId, fn, startTime: Date.now(), delayTime: waitTime, args })
  const eventLoop = () => {
    
    for (let i = 0, len = taskQueue.length; i < len; i++) {
      const { fn, startTime, delayTime, args } = taskQueue[i] || {}
      // const now = Date.now()
      if (Date.now() - startTime >= delayTime) {
        fn.call(this, ...args)
        taskQueue[i].startTime = Date.now()
        // taskQueue[i] = null
      }
    }
    // taskQueue = taskQueue.filter((t) => !!t)
    requestAnimationFrame(eventLoop)
  }
  eventLoop()
  return timerId
}

function clearInterval(timer) {
  taskQueue = taskQueue.filter((t) => t.timerId !== timer)
}

var timer = setInterval((a,b) => console.log(a,b),5000,1,2)